#include "StringHash.h"
#include <cstdio>

const StringHash StringHash::ZERO;

inline constexpr unsigned SDBMHash(unsigned hash, unsigned char c) { return c + (hash << 6u) + (hash << 16u) - hash; }
static const int CONVERSION_BUFFER_LENGTH = 128;

StringHash::StringHash(const char* str) noexcept :
	value_(Calculate(str))
{

}

StringHash::StringHash(const std::string& str) noexcept :
	value_(Calculate(str.c_str()))
{

}

unsigned StringHash::Calculate(const char* str, unsigned hash)
{
	if (!str)
		return hash;

	while (*str)
	{
		hash = SDBMHash(hash, (unsigned char)*str++);
	}

	return hash;
}

std::string StringHash::ToString() const
{
	char tempBuffer[CONVERSION_BUFFER_LENGTH];
	sprintf(tempBuffer, "%08X", value_);
	return std::string(tempBuffer);
}


